﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 知识文档
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017-12-08 
    /// </summary>
    internal class DocumentService : DataFactory, DocumentIService
    {
        /// <summary>
        /// 列表（全部文件夹）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<List<DocumentEntity>> GetFolderList(string userId)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<DocumentEntity>().Where(m => m.CreatorUserId == userId && m.Type == 0).OrderBy(o => o.CreatorTime).ToListAsync();
            }
        }
        /// <summary>
        /// 列表（全部下级数据）
        /// </summary>
        /// <param name="userId">文件夹主键</param>
        /// <returns></returns>
        public async Task<List<DocumentEntity>> GetChildList(string folderId)
        {
            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                StringBuilder dbSql = new StringBuilder();
                var dbParameters = new DbParameters();
                dbSql.Append(@"WITH document AS (
		                                SELECT *
		                                FROM Ext_Document
		                                WHERE F_Id = @folderId
		                                UNION ALL
		                                SELECT Ext_Document.*
		                                FROM document, Ext_Document
		                                WHERE document.F_Id = Ext_Document.F_ParentId
	                                )
                                SELECT *
                                FROM document");
                parameters.Add(DataHelper.CreateParameter("@folderId", folderId));
                return await db.GetListSqlAsync<DocumentEntity>(dbSql.ToString(), parameters.ToArray());
            }
        }
        /// <summary>
        /// 列表（全部文档）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="parentId">文档父级</param>
        /// <returns></returns>
        public async Task<List<DocumentEntity>> GetAllList(string userId, string parentId)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<DocumentEntity>().Where(m => m.CreatorUserId == userId && m.ParentId == parentId && m.DeleteMark == 0).OrderBy(o => o.CreatorTime).ToListAsync();
            }
        }
        /// <summary>
        /// 列表（回收站）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<List<DocumentEntity>> GetTrashList(string userId)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<DocumentEntity>().Where(m => m.CreatorUserId == userId && m.DeleteMark == 1).OrderBy(o => o.CreatorTime).ToListAsync();
            }
        }
        /// <summary>
        /// 列表（我的共享）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<List<DocumentEntity>> GetShareOutList(string userId)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<DocumentEntity>().Where(m => m.CreatorUserId == userId && m.DeleteMark == 0 && m.IsShare > 0).OrderBy(o => o.CreatorTime).ToListAsync();
            }
        }
        /// <summary>
        /// 列表（共享给我）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<List<DocumentEntity>> GetShareTomeList(string userId)
        {
            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                DbParameters dbParameters = new DbParameters();
                StringBuilder dbSql = new StringBuilder();
                dbSql.Append(@"SELECT *
                                FROM Ext_Document
                                WHERE F_Id IN (SELECT F_DocumentId
	                                FROM Ext_DocumentShare
	                                WHERE F_ShareUserId = @userId) AND F_DeleteMark = 0");
                parameters.Add(DataHelper.CreateParameter("@userId", userId));
                return await db.GetListSqlAsync<DocumentEntity>(dbSql.ToString(), parameters.ToArray());
            }
        }
        /// <summary>
        /// 列表（共享人员）
        /// </summary>
        /// <param name="documentId">文档主键</param>
        /// <returns></returns>
        public async Task<List<DocumentShareEntity>> GetShareUserList(string documentId)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<DocumentShareEntity>().Where(m => m.DocumentId == documentId).ToListAsync();
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<DocumentEntity> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<DocumentEntity>(m => m.Id == id);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(DocumentEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.DeleteAsync(entity);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entitys">实体对象</param>
        public async Task Delete(List<DocumentEntity> entitys)
        {
            using (var db = this.Basic)
            {
                if (entitys.Count > 0)
                {
                    await db.BeginTransactionAsync();
                    foreach (DocumentEntity entity in entitys)
                    {
                        await db.DeleteAsync(entity);
                    }
                    await db.CommitTransactionAsync();
                }
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(DocumentEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(DocumentEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(entity);
            }
        }
        /// <summary>
        /// 共享文件（创建）
        /// </summary>
        /// <param name="documentId">文档主键</param>
        /// <param name="entity">共享人员</param>
        public async Task ShareCreate(string documentId, List<DocumentShareEntity> entitys)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();
                DocumentEntity documentEntity = await db.GetEntityAsync<DocumentEntity>(m => m.Id == documentId);
                documentEntity.IsShare = entitys.Count;
                documentEntity.ShareTime = DateTime.Now;
                await db.UpdateAsync(documentEntity);
                await db.DeleteAsync<DocumentShareEntity>(m => m.DocumentId == documentId);
                await db.InsertAsync(entitys);
                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 共享文件（取消）
        /// </summary>
        /// <param name="documentId">文档主键</param>
        public async Task ShareCancel(string documentId)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();
                DocumentEntity documentEntity = await db.GetEntityAsync<DocumentEntity>(m => m.Id == documentId);
                documentEntity.IsShare = 0;
                documentEntity.ShareTime = DateTime.Now;
                await db.UpdateAsync(documentEntity);
                await db.DeleteAsync<DocumentShareEntity>(m => m.DocumentId == documentId);
                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns></returns>
        public async Task<bool> IsExist(Expression<Func<DocumentEntity, bool>> condition)
        {
            using (var db = this.Basic)
            {
                return await db.GetCountAsync(condition) > 0;
            }
        }
    }
}